import pyautogui
from PIL import ImageGrab
import pytesseract
import easyocr
import time
import numpy as np

pytesseract.pytesseract.tesseract_cmd = r'F:\PyProjects\Tesseract-OCR\tesseract.exe'  # Windows 示例
reader = easyocr.Reader(['en', 'ch_sim'], gpu=True)  # 支持多语言
# 捕捉屏幕图像
screenshot = None

def GetScreenRes():
    start_time = time.time()  # 记录开始时间
    screenshot = ImageGrab.grab()
    screenshot_np = np.array(screenshot)
    result = reader.readtext(screenshot_np)
    end_time = time.time()  # 记录结束时间
    elapsed_time = end_time - start_time  # 计算耗时
    print(f"本次屏幕识别耗时: {elapsed_time:.6f} 秒")
    return result

def MouseMoveToText(matchText, offset_x=0, offset_y=0):
    result = GetScreenRes()
    for detection in result:
        bbox = detection[0]
        detected_text = detection[1]
        if detected_text.find(matchText) > -1:
            # 获取该文字的中心点
            x1, y1 = bbox[0]
            x3, y3 = bbox[2]
            center_x = (x1 + x3) / 2 + offset_x
            center_y = (y1 + y3) / 2 + offset_y
            
            # 移动鼠标到该文字的中心
            pyautogui.moveTo(center_x, center_y, duration=2)
            pyautogui.click();
            print(f"鼠标移动到指定文字位置'：({center_x}, {center_y})")
            return True
    return False

def MatchTextList(matchText):
    result = GetScreenRes()
    list = []
    for detection in result:
        bbox = detection[0]
        detected_text = detection[1]
        if detected_text.find(matchText) > -1:
            # 获取该文字的中心点
            x1, y1 = bbox[0]
            x3, y3 = bbox[2]
            center_x = (x1 + x3) / 2
            center_y = (y1 + y3) / 2
            list.append({'text': detected_text, 'center_x': center_x, 'center_y': center_y})
    return list
